import { useReactive } from "ahooks";
import { useModel } from "umi";
import { useEffect } from "react";
import compress from "gql-compress";

const useGlobalSetting = () => {
    const { graphqlFetch } = useModel("global");

    const state = useReactive({
        loading: false,
        globalSettings: {},
    });

    const loadData = async (isReload = false) => {
        let cacheKey = window.organizationUuid + "-globalSettings";
        if (isReload === false) {
            let cacheData = nodeCache.get(cacheKey);
            if (cacheData) {
                state.globalSettings = cacheData || {};
                return cacheData || {};
            }
        }
        state.loading = true;
        let res = await graphqlFetch({
            query: AllGlobalSettings,
            variables: {},
        });
        let newData = {};
        if (res) {
            let globalSettings = res?.a?.nodes || [];
            globalSettings.forEach((item) => {
                newData[item.gsKey] = item.gsType === "json" ? item.gsJson : item.gsValue;
            });
            state.globalSettings = newData;
            nodeCache.set(cacheKey, newData, 2 * 60); // 缓存两分钟
        }
        state.loading = false;
        return newData;
    };

    useEffect(() => {
        loadData();
    }, []);

    return { ...state, loadGlobalSettings: loadData };
};

const AllGlobalSettings = compress(`query MyQuery {
    a: allGlobalSettings {
        nodes {
            gsJson
            gsKey
            gsType
            gsValue
        }
    }
}`);

export default useGlobalSetting;
